#!/usr/bin/python
# -*- coding: utf-8 -*-

import Ice, IceGrid
import os, sys, time

try:
    HOME = os.environ['FIPA']
except KeyError:
    print 'FIPA environment variable is not currently defined.'
    sys.exit(0)

SLICE = os.path.join(HOME, 'slice')
FILE1 = os.path.join(SLICE, 'FIPA.ice')
Ice.loadSlice('--all -I/usr/share/slice', ['-I' + SLICE, FILE1])

import FIPA, PropertyService, P

class AMI_Model_receiveMessageI (object):

    def ice_response (self):
        pass

    def ice_exception (self, ex):
        pass

class Client (Ice.Application):

    def run (self, argv):

        queryPrx = IceGrid.QueryPrx.checkedCast(self.communicator().stringToProxy('FIPA/Query'))

        factory = FIPA.AgentFactoryPrx.checkedCast(queryPrx.findObjectByType('::FIPA::AgentFactory'))

        prx1 = factory.create('')
        prx2 = factory.create('')

        mts = FIPA.MTSPrx.checkedCast(queryPrx.findObjectById(self.communicator().stringToIdentity('MTS')))

        env = FIPA.Envelope([prx2], prx1)
        pay = FIPA.ACLPayload()
        m = FIPA.Message(env, pay)

        mts.receiveMessage_async(AMI_Model_receiveMessageI(), m)

        #factory = FIPA.AgentFactoryPrx.checkedCast(queryPrx.findObjectById(self.communicator().stringToIdentity('AgentFactory.1')))
        #agent = factory.create('')
        #print agent

        #factoryPrx = PropertyService.PropertySetFactoryPrx.checkedCast(
        #    self.communicator().stringToProxy('propertySetFactory:default -p 9999'))
        #aux = {}
        #aux['z'] = P.IntT(1)
        #prx = factoryPrx.createInitialPropertySet(aux)

        #prx.deleteAllProperties()
        #prx.defineProperty('a', P.IntT(1))

        #try:
        #    prx.defineProperty('a', P.StringT('1'))
        #except PropertyService.UnsupportedTypeCode:
        #    pass

        #print prx.getNumberOfProperties()

        #properties = {}
        #properties['b'] = P.BoolT(True)
        #properties['c'] = P.FloatT(1.0)
        #prx.defineProperties(properties)

        #print prx.getNumberOfProperties()

        #theNames, it = prx.getAllPropertyNames(1)
        #for n in theNames:
        #    print 'Name: ' + n
        #if it:
        #    more, names = it.nextN(3)
        #    if more:
        #        for n in names:
        #            print 'Name (thru the iterator): ' + n
        #    else:
        #        print 'No more names (thru the iterator)'
        #    it.destroy()

        #theProperties, it = prx.getAllProperties(6)
        #for key, value in theProperties.iteritems():
        #    print key, '=', value.value
        #if it:
        #    more, names = it.nextN(3)
        #    if more:
        #        for n in names:
        #            print 'Name (thru the iterator): ' + n
        #    else:
        #        print 'No more names (thru the iterator)'
        #    it.destroy()
            
        #print prx.getPropertyValue('b').value
        #try:
        #    print prx.getPropertyValue('x').value
        #except PropertyService.PropertyNotFound:
        #    pass

        #theNames = ['a', 'c']
        #v, props = prx.getProperties(theNames)
        #if v:
        #    for p in props.values():
        #        print p.value

        #prx.deleteProperty('a')
        #print prx.getNumberOfProperties()
        #try:
        #    prx.deleteProperty('a')
        #except PropertyService.PropertyNotFound:
        #    pass
        
        #try:
        #    prx.deleteProperties(theNames)
        #except PropertyService.MultipleExceptions, ex:
        #    for e in ex.exceptions:
        #        print e.failingPropertyName, e.reason

        #print prx.isPropertyDefined('c')

        #aidPrx = factory1.create(self.communicator().stringToIdentity('david'))
        #aidPrx.setAddresses([aidPrx])

        #sdPrx = factory2.create('surveillance', 'movements')

        #dfPrx = factory3.create(aidPrx)
        #dfPrx.setServices([sdPrx])
        #dfPrx.setProtocols(['fipa-request', 'fipa-contract-net'])
        #dfPrx.setLeaseTime(3600)
        #print dfPrx.describe()

        #mts = FIPA.MTSPrx.checkedCast(
        #    self.communicator().stringToProxy('MTS'))

        #factory = FIPA.AgentFactoryPrx.checkedCast(
        #    self.communicator().stringToProxy('AgentFactory1'))

        #prx1 = factory.create('')
        #prx2 = factory.create('')

        #env = FIPA.Envelope([prx2], prx1)
        #pay = FIPA.ACLPayload()
        #m = FIPA.Message(env, pay)

        #mts.receiveMessage_async(AMI_Model_receiveMessageI(), m)

        #prxs = []
        #names = []
        #for i in range (1, 10):
        #    names.append('Agent' + str(i))
            
        #prxs, namesAlreadyRegistered = factory.createSeq(names)

        #print '** Destroying...'
        #for prx in prxs:
        #    prx.destroy()

        #ag2 = factory.create('alba')
        #receivers = []
        #for i in range (0, 8):
        #    receivers.append(factory.create(''))

        #m = FIPA.ACLMessage(FIPA.ACLPerformative.Request, ag1, receivers)

        #for r in receivers:
        #    print '...........'
        #    print 'Sending to: ' + str(r)
        #    print '...........'
        #    for i in range (1, 5):
        #        r.receiveMessage_async(AMI_Model_receiveMessageI(), m)

        #print '...........'
        #print 'Creating...'
        #print '...........'
        #for i in range(0, 10):
        #    amsPrx.create('')

        #print '..............'
        #print 'Discovering...'
        #print '..............'
        #for agent in amsPrx.list():
        #    agent.discover()

        #    time.sleep(1)
        #agent1 = amsPrx.create('david')
        #agent2 = amsPrx.create('david')
        #agent1.discover()
        #agent1.destroy()
        #agent2 = amsPrx.create('')

        return 0

Client().main(sys.argv, '../config/config.client')
